import 'package:flutter/services.dart';
import 'package:flutter/foundation.dart';

/// 🔥 微信分享服务
/// 
/// 通过Method Channel调用原生微信SDK实现真正的微信分享功能
class WeChatShareService {
  static const MethodChannel _channel = MethodChannel('wechat_share');
  
  /// 检查微信是否已安装
  static Future<bool> isWeChatInstalled() async {
    try {
      final bool? result = await _channel.invokeMethod('isWeChatInstalled');
      debugPrint('📱 微信安装状态: $result');
      return result ?? false;
    } catch (e) {
      debugPrint('❌ 检查微信安装状态失败: $e');
      return false;
    }
  }
  
  /// 分享网页到微信
  /// 
  /// [title] 分享标题
  /// [description] 分享描述
  /// [webUrl] 分享链接
  /// [thumbUrl] 缩略图URL（可选）
  /// [isTimeline] 是否分享到朋友圈（false=分享给好友）
  /// 
  /// 返回是否成功调起微信
  static Future<bool> shareToWeChat({
    required String title,
    required String description,
    required String webUrl,
    String? thumbUrl,
    required bool isTimeline,
  }) async {
    try {
      debugPrint('💬 =============== 开始调用原生微信分享 ===============');
      debugPrint('📝 标题: $title');
      debugPrint('📝 描述: $description');
      debugPrint('🌐 链接: $webUrl');
      debugPrint('🖼️ 缩略图: $thumbUrl');
      debugPrint('📍 场景: ${isTimeline ? "朋友圈" : "好友"}');
      
      // 检查微信是否安装
      final installed = await isWeChatInstalled();
      if (!installed) {
        debugPrint('❌ 微信未安装，无法分享');
        return false;
      }
      
      final Map<String, dynamic> arguments = {
        'title': title,
        'description': description,
        'webUrl': webUrl,
        'thumbUrl': thumbUrl,
        'isTimeline': isTimeline,
      };
      
      final bool? result = await _channel.invokeMethod('shareToWeChat', arguments);
      
      if (result == true) {
        debugPrint('✅ 微信分享请求发送成功');
      } else {
        debugPrint('❌ 微信分享请求发送失败');
      }
      
      return result ?? false;
      
    } on PlatformException catch (e) {
      debugPrint('💥 微信分享异常（PlatformException）');
      debugPrint('   代码: ${e.code}');
      debugPrint('   消息: ${e.message}');
      debugPrint('   详情: ${e.details}');
      return false;
    } catch (e) {
      debugPrint('💥 微信分享异常: $e');
      return false;
    }
  }
}

